package au.com.bus4u.controller;


import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import au.com.bus4u.exception.ServiceException;
import au.com.bus4u.utils.DateUtil;
import au.com.bus4u.utils.FileUtil;
import au.com.bus4u.utils.JsonResult;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller
@RequestMapping("/fileUpload")
@Log
public class FileUploadController extends BaseController {
    @Autowired
    private HttpServletRequest request;

    @Value("${upload.file.path}")
    private String uploadFilePath;//文件保存磁盘路径


    @Value("${spring.profiles.serverUrl}")
    private String serverUrl;//项目访问路径

    @Value("${spring.profiles.uploads}")
    private String uploads;//图片访问路径


    @RequestMapping("/img")
    @ResponseBody
    public JsonResult<Map> upload(@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException{
        log.info("=========================================");
        String fileName = file.getOriginalFilename();
        String type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
//        System.err.println("文件格式: " + type);
        if(type == null) {
            throw new ServiceException("文件格式错误!");
        }
        String filePath = DateUtil.formatDate(new Date(), "yyyy-MM-dd")+ "/";// 把文件名子换成（时间搓.png）
        String imageName = DateUtil.formatDate(new Date(), "yyyyMMddHHmm_ssSSS") + "_" + get32UUID()+"."+type;
        FileUtil.makeDirs(uploadFilePath + filePath);// 检测文件夹

        File dest=new File(uploadFilePath+filePath + imageName);

        // 将上传的文件保存到指定的路径
        file.transferTo(dest);


        Map<String, Object> result = new HashMap<>();
        result.put("url", "/"+uploads+filePath + imageName);
//        result.put("url1", serverUrl+uploads+filePath + imageName);
//        result.put("url2", uploadFilePath+filePath+imageName);

        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        String size = decimalFormat.format( (double)file.getSize()/1024);
        result.put("size",size+"KB");
        result.put("oldFileName", file.getOriginalFilename());

        return new JsonResult<Map>(SUCCESS, result);
    }







}